package com.wf.course.service.impl;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.utils.page.PageBean;
import com.wf.course.dao.ISpeakerMapper;
import com.wf.course.model.course.Speaker;
import com.wf.course.service.ISpeakerService;
import com.wf.course.web.Constants;
import com.wf.course.web.OSSUtil;

@Service
@Transactional(rollbackFor=Exception.class)
public class ISpeakerServiceImpl implements ISpeakerService{
	
	@Autowired
	private ISpeakerMapper mapper;

	@Override
	public void indexInfo(PageBean<Speaker> pageBean) {
		// TODO Auto-generated method stub
		pageBean.setResults(this.mapper.queryList(pageBean));
		pageBean.setTotalCount(this.mapper.getTotalCount(pageBean).intValue());
	}

	@Override
	public void saveOrUpdateSpeaker(Speaker speaker,MultipartFile imageFile ) {
		// TODO Auto-generated method stub
		
		//添加
		if(speaker.getId()==null){
			//创建时间
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			speaker.setCreateTime(df.format(new Date()));
			
			if (!imageFile.isEmpty()) {
				String speakerImage = "";
				try {
					speakerImage = OSSUtil.addFile(imageFile, "wf_course/speakerImage", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				speaker.setSpeakerImage(speakerImage);
			}
			
			
			this.mapper.saveSpeaker(speaker);
		}else{
		 //修改
			if (imageFile.getSize() != 0) {
				Speaker spk = mapper.querySpeakerById(speaker.getId());
				try{
					if(StringUtils.isNotBlank(spk.getSpeakerImage())){
						// 删除原来头像
						OSSUtil.delete(spk.getSpeakerImage(), Constants.IGM_BUCKET);
					}
				}catch(Exception e){
					System.out.println(e.getMessage());
				}
				// 重新上传
				// 上传
				String speakerImage = "";
				try {
					speakerImage = OSSUtil.addFile(imageFile, "wf_course/speakerImage", Constants.IGM_BUCKET);
				} catch (IOException e) {
					e.printStackTrace();
				}
				speaker.setSpeakerImage(speakerImage);
			}
			
		  this.mapper.updateSpeaker(speaker);
			
		}
	}

	@Override
	public Speaker querySpeakerById(Integer id) {
		// TODO Auto-generated method stub
		return this.mapper.querySpeakerById(id);
	}

	@Override
	public void deleteById(Integer id) {
		// TODO Auto-generated method stub
		this.mapper.deleteById(id);
	}
	@Override
	public List<Speaker> queryteacher() {
		// TODO Auto-generated method stub
		return this.mapper.queryteacher();
	}
	
	
}
